import React, { useLayoutEffect, useState } from 'react';

import { ActivityIndicator, InputItem, Modal, Toast } from 'antd-mobile';
import { createForm } from 'rc-form';
import { useMount } from 'react-use';
import { router, withRouter } from 'umi';

import { defaultFormatResult, useRequest } from '@/hooks';
import useDictionary from '@/hooks/useDictionary';
import CustomNavBar from '@/pages/EntryManage/mobile/components/CustomNavBar';
import EntryMetaTag from '@/pages/EntryManage/mobile/components/EntryMetaTag';
import { deleteSkillById, getSkillById, saveSkillsSingle } from '@/pages/EntryManage/services';
import { useFormChange } from '@/pages/RecruitEmail/hooks';
import { Button, EditListItem, Picker } from '@/pages/RecruitEmail/mobile/components';

import styles from './index.less';

/**
 * 入职员工专业技能
 */
const EntryEmployeeSkillsMobile = ({ form, location }) => {
    const [pageError, setPageError] = useState();
    const { query } = location;
    const { entryPersonnelCode, id } = query;
    const { getFieldProps, resetFields } = form;
    const [skillLevelOptions] = useDictionary('skill_level', { textKey: 'label' });
    const { hasFormChange, initialForm } = useFormChange(form);
    // 获取数据
    const { data: formData, loading: formDataLoading, error: formDataError } = useRequest(() => getSkillById(id), {
        refreshDeps: [id],
        ready: !!id,
        ...defaultFormatResult,
        onSuccess: () => {
            initialForm();
        }
    });
    useMount(() => {
        if (!id) {
            initialForm();
        }
    });
    // 提交
    const { run: submitRun, loading: submitLoading } = useRequest(submitData => saveSkillsSingle(submitData), {
        manual: true
    });

    // 提交
    const handleSubmit = isContinueAdd => {
        form.validateFields((err, values) => {
            if (!err) {
                const submitData = {
                    entryPersonnelCode,
                    id,
                    skillName: values.skillName ? values.skillName : null,
                    skillDuration: values.skillDuration ? values.skillDuration : null,
                    proficiency: values.proficiency?.length ? values.proficiency[0] : null
                };
                // 提交
                submitRun(submitData).then(res => {
                    if (res.code === 10000) {
                        Toast.info('保存成功', 3, null, false);
                        if (isContinueAdd) {
                            resetFields();
                        } else {
                            history.goBack();
                        }
                    } else {
                        Toast.info(res.msg);
                    }
                });
            } else {
                const errorList = Object.values(err);
                if (errorList && errorList.length > 0) {
                    const { errors } = errorList[0];
                    Toast.info(errors[0]?.message, 3, null, false);
                }
            }
        });
    };

    // 删除
    const handleDelete = isContinueAdd => {
        if (!id) {
            return;
        }
        Toast.loading('提交中...', 5000);
        deleteSkillById({ entryPersonnelCode, id })
            .then(res => {
                const { code, msg } = res;
                if (code === 10000) {
                    Toast.info('删除成功', 3, null, false);
                    if (isContinueAdd) {
                        resetFields();
                    } else {
                        history.goBack();
                    }
                } else {
                    Toast.info(msg);
                }
            })
            .finally(() => {
                Toast.hide();
            });
    };

    const handleLeftClick = () => {
        if (hasFormChange()) {
            Modal.alert('存在未保存的内容，确定退出吗？', '', [
                { text: '取消' },
                {
                    text: '确定',
                    onPress: () => {
                        history.goBack();
                    }
                }
            ]);
        } else {
            history.goBack();
        }
    };

    useLayoutEffect(() => {
        // 参数校验
        if (!entryPersonnelCode) {
            setPageError('参数无效');
        }
    }, [entryPersonnelCode]);

    if (pageError || formDataError) {
        return <div className={styles.pageError}>{pageError?.msg || formDataError?.msg || '加载错误'}</div>;
    }

    return (
        <>
            {(formDataLoading || submitLoading) && <ActivityIndicator toast text="正在加载" />}
            {!id || formData ? (
                <div className={styles.entryMobileContainer}>
                    <EntryMetaTag />
                    <CustomNavBar onLeftClick={handleLeftClick}>专业技能</CustomNavBar>
                    <div className="formContainer formContainerFixed">
                        <EditListItem title="技能名称" showArrow={false}>
                            <InputItem
                                {...getFieldProps('skillName', {
                                    initialValue: formData?.skillName || '',
                                    rules: [
                                        { required: true, message: '请填写技能名称' },
                                        { max: 50, message: '字数不能超过50个字符' }
                                    ]
                                })}
                                clear
                                placeholder="请输入"
                            />
                        </EditListItem>
                        <EditListItem title="技能使用时长(月)(选填)" showArrow={false}>
                            <InputItem
                                type="number"
                                {...getFieldProps('skillDuration', {
                                    initialValue: formData?.skillDuration || ''
                                })}
                                extra="月"
                                clear
                                placeholder="请输入"
                            />
                        </EditListItem>
                        <Picker
                            title="掌握程度"
                            className={styles.customPicker}
                            data={skillLevelOptions}
                            cols={1}
                            {...getFieldProps('proficiency', {
                                initialValue: formData?.proficiency ? [formData?.proficiency?.toString()] : undefined
                            })}
                        >
                            <EditListItem title="掌握程度(熟练度)(选填)">请选择</EditListItem>
                        </Picker>
                    </div>
                    <div className="formControls">
                        {query?.id ? (
                            <>
                                <Button style={{ marginRight: 15, flex: 1 }} onClick={handleDelete}>
                                    删除
                                </Button>
                                <Button type="primary" style={{ flex: 1 }} onClick={handleSubmit}>
                                    完成
                                </Button>
                            </>
                        ) : (
                            <>
                                <Button style={{ marginRight: 15, flex: 1 }} onClick={handleSubmit}>
                                    保存
                                </Button>
                                <Button type="primary" style={{ flex: 1 }} onClick={() => handleSubmit(true)}>
                                    保存并继续添加
                                </Button>
                            </>
                        )}
                    </div>
                </div>
            ) : null}
        </>
    );
};

export default withRouter(createForm()(EntryEmployeeSkillsMobile));
